package com.common.app.widget

import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.common.app.data.bean.FloatWindowConfig
import com.common.app.databinding.ViewFloatWindowBinding
import com.common.app.helper.LaunchHelper
import com.common.base.utils.SpUtilsManagement
import com.common.base.app.extras.OnImageLoadListener
import com.common.base.app.extras.load
import com.common.base.utils.LogUtils

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：14/2/2023
 *
 * 描述：固定悬浮窗
 *
 * 修订历史：
 *
 */
class ActivityFloatWindowView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, spKey: String = "") : FrameLayout(context, attrs, defStyleAttr) {

    val mViewBinding = ViewFloatWindowBinding.inflate(LayoutInflater.from(context), this, true)

    init {
        mViewBinding.apply {
            ivClose.setOnClickListener {
                isGone = true
                if (spKey.isNullOrEmpty().not()){
                    //更改标识
                    SpUtilsManagement.putBoolean(spKey, false)
                }
            }
        }
        isVisible = false //默认为隐藏
    }

    fun setData(config: FloatWindowConfig){
        mViewBinding.ivImg.setOnClickListener {
            if (config.linkUrl.isNullOrEmpty().not()){
                LaunchHelper.launchWebActivity(config.linkUrl)
            }
        }

        config.gifFromAssets?.let {
            //asset file
            mViewBinding.ivImg.setImageDrawable(it)
            //图片加载成功 设置为可见
            isVisible = true
            return
        }

        mViewBinding.ivImg.load(config.logoUrl, listener = object: OnImageLoadListener{
            override fun onSuccess(bitmap: Drawable?) {
                //图片加载成功 设置为可见
                isVisible = true
                LogUtils.e("ActivityFloatWindowView", "onSuccess")
            }

            override fun onFail(msg: String) {
                LogUtils.e("ActivityFloatWindowView", "onFail: $msg")
            }
        })
    }
}